package net.yunxinyong.cec.service.impl;

import net.yunxinyong.cec.entity.EcnomicBrances;
import net.yunxinyong.cec.entity.EcnomicInventory;
import net.yunxinyong.cec.mapper.EcnomicBrancesMapper;
import net.yunxinyong.cec.mapper.EcnomicInventoryDetailMapper;
import net.yunxinyong.cec.mapper.EcnomicInventoryMapper;
import net.yunxinyong.cec.service.BranceService;
import net.yunxinyong.cec.service.InventoryService;
import net.yunxinyong.cec.utils.CecException;
import net.yunxinyong.cec.utils.ListUtils;
import net.yunxinyong.cec.vo.EcnomicInventoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private EcnomicInventoryDetailMapper ecnomicInventoryDetailMapper;
    @Autowired
    private EcnomicBrancesMapper ecnomicBrancesMapper;
    @Autowired
    private BranceService branceService;

    @Override
    public EcnomicInventoryVo insertAndUpdate(EcnomicInventoryVo ecnomicInventoryVo) {
        //添加详情表

        Long parentId = ecnomicInventoryVo.getId();
        ecnomicInventoryVo.setId(null);
        ecnomicInventoryVo.setParentId(parentId);
        ecnomicInventoryVo.setCreatetime(new Date());
        if (ecnomicInventoryVo.getEstablishmentTime() == null){
            ecnomicInventoryVo.setEstablishmentTime(new Date());
        }

        int insertSelective = ecnomicInventoryDetailMapper.insertSelective(ecnomicInventoryVo);
        if (insertSelective <= 0){
            return null;
        }
        //添加分支表
        if (!ListUtils.isEmpty(ecnomicInventoryVo.getBrancesList())){
            //id是插入后返回来的新id
            branceService.insertList(ecnomicInventoryVo.getBrancesList(),ecnomicInventoryVo.getId());
        }

        //修改主表状态
        EcnomicInventory ecnomicInventory = new EcnomicInventory();
        ecnomicInventory.setId(parentId);
        ecnomicInventory.setUiteStatus(1);
        ecnomicInventoryMapper.updateByPrimaryKeySelective(ecnomicInventory);
        //返回添加状态
        return ecnomicInventoryVo;
    }

}
